package com.baozhun.mall.common.widget.viewpager

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.viewpager.widget.ViewPager
import java.util.LinkedHashMap

/**
 * @Title：自适应高度viewpage
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2022/11/26
 * @Version：1.0.0
 */
class WrapViewPager : ViewPager {
    private var mCurrent = 0
    private var mViewHeight = 0

    /**
     * 保存position与对于的View
     */
    private val mChildrenViews = LinkedHashMap<Int, View>()

    constructor(context: Context?) : super(context!!, null)

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs)

    /**
     *  切换tab的时候重新设置viewpager的高度
     */
    fun resetHeight(current: Int) {
        this.mCurrent = current
        if (mChildrenViews.size > current) {
            var layoutParams = layoutParams as LinearLayout.LayoutParams
            if (layoutParams == null) {
                layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, mViewHeight)
            } else {
                layoutParams.height = mViewHeight
            }
            setLayoutParams(layoutParams)
        }
    }

    /**
     * 保存position与对于的View
     */
    fun setObjectForPosition(view: View, position: Int) {
        mChildrenViews[position] = view
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var heightMeasureSpec = heightMeasureSpec
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (mChildrenViews.size > mCurrent) {
            val child = mChildrenViews[mCurrent]
            child?.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
            mViewHeight = child?.measuredHeight!!
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(mViewHeight, MeasureSpec.EXACTLY)
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}